package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.*;
import com.fuershiye.woman.monitor.constants.CodeName;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Area;
import com.fuershiye.woman.monitor.model.Indicator;
import com.fuershiye.woman.monitor.service.*;
import com.fuershiye.woman.monitor.utils.DateFormatUtil;
import com.fuershiye.woman.monitor.utils.MyUtilString;
import com.fuershiye.woman.monitor.utils.ReportUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 按年份进行报表的查询
 * 
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/report/prealarm")
public class ReportPreAlarmController {

	private static final Logger logger = LoggerFactory
			.getLogger(ReportPreAlarmController.class);

	@Autowired
	ReportService reportService;
	@Autowired
	IndicatorService indicatorService;
	@Autowired
	DepartmentService departmentService;
	@Autowired
	AreaService areaService;
    @Autowired
    FormsService formsService;


	@RequestMapping(value = "/prealarmConfigView.do")
	public String prealarmConfig(Model model, String show) {
		model.addAttribute("level", show);

		List<Integer> years = DateFormatUtil.getAreaYears();
		model.addAttribute("years", years);

        List<IdName> formes = formsService.getAllNames();
        // 表 forms 的ID ： 1:妇儿 2:社会
        model.addAttribute("formes", formes);

		return "preAlarm/config/" + show;
	}

	@RequestMapping(value = "/prealarmView.do")
	public String preAlarm(Model model, String show) {
		model.addAttribute("level", show);

		List<Integer> years = DateFormatUtil.getAreaYears();
		model.addAttribute("years", years);

        List<IdName> formes = formsService.getAllNames();
        // 表 forms 的ID ： 1:妇儿 2:社会
        model.addAttribute("formes", formes);

		return "preAlarm/" + show;
	}

	@RequestMapping(value = "/monitorView.do")
	public String monitorView(String show, Model model) {

		List<Integer> years = DateFormatUtil.getAreaYears();
		model.addAttribute("years", years);

		return "monitor/" + show;
	}

	/**
	 * 5.1、同领域,省级部门,多年份,模糊查询
	 *
	 * 同领域,省级部门,多年份,模糊查询【有背景颜色】
	 *
	 * @param indicatorType【必传：-1表示全部】
	 * @param iname	【非必传,模糊指标名称查询】
	 * @param years 【必传，用英文逗号隔开的年份  2011,2012,2013】
	 * @param page	【非必传】
	 * @param pageSize	【非必传】
	 * @return	返回值是value_color
	 *
	 * 适用场景【省级数据预警】
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("report:preAlarm")
	@RequestMapping(value = "/province.do")
	@ResponseBody
	public Result province(Long formsid, String indicatorType, String departId, String iname, String years, Integer page, Integer pageSize) {

		if(formsid==null||formsid == 0 || StringUtils.isBlank(indicatorType) || StringUtils.isBlank(years)) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Integer> yearList = DateFormatUtil.getYearStr2List(years);
		if(yearList.isEmpty()){
			return new Result(Massage.ERROR_YEAR);
		}

		List<Long> indicatorTypeIds = Lists.newArrayList();
		if(indicatorType.equals("-1")){
			indicatorTypeIds = null;
		}else{
			indicatorTypeIds = MyUtilString.str2LongByPlaceHolder(indicatorType, ",");
		}

		// 查找所有的指标
		List<Indicator> indicatorAll = indicatorService.listByCondition(iname, formsid, indicatorTypeIds, 1, null, 1, null);
		List<Long> indicatorIds = indicatorService.getIndicatorId(indicatorAll);
		if (indicatorIds.isEmpty()) {
			return new Result(Massage.INDICATOR_IS_NULL);
		}

		List<Long> departIds = Lists.newArrayList();
		if(StringUtils.isBlank(departId)|| departId.equals("-1")){
			// 查找所有省级的部门
			List<IdNameSname> departmentList = departmentService.getAllByLevelAndArea(2, null, 1);
			departIds = departmentService.getDepartIdsFromIdNameSname(departmentList);
		}else{
			departIds=MyUtilString.str2LongByPlaceHolder(departId, ",");
		}
		if (departIds.size()<1) {
			return new Result(Massage.DEPART_IS_NULL);
		}

		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicatorIds, yearList, 1);
		List<Map<String, Object>> result = reportService.filter(reportList, yearList);

		return new Result(Massage.SUCCESS, new PageResult(result, result.size()));
	}

	/**
	 * 5.2、同地域,多年份,模糊查询
	 *
	 * 同地域,多年份,模糊查询【有背景颜色】
	 *
	 * @param areaid【必传,地域】
	 * @param iname	【非必传,模糊指标名称查询】
	 * @param indicatorType【必传：-1表示全部】
	 * @param years 【必传，用英文逗号隔开的年份  2011,2012,2013】
	 * @param page	【非必传】
	 * @param pageSize	【非必传】
	 * @return	返回值是value_color
	 *
	 * 适用场景【相同地域下,同领域的数据预警】
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("report:preAlarm")
	@RequestMapping(value = "/area.do")
	@ResponseBody
	public Result area(Long areaid, String departId, String iname, Long formsid, String indicatorType, String years, Integer page, Integer pageSize) {

 		if(areaid==null||areaid == 0 || formsid==null||formsid == 0 ||
				StringUtils.isBlank(indicatorType)  || StringUtils.isBlank(years)) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Integer> yearList = DateFormatUtil.getYearStr2List(years);
		if(yearList.isEmpty()){
			return new Result(Massage.ERROR_YEAR);
		}
		if(areaid==-1){
			areaid = null;
		}

		List<Long> indicatorTypeIds = Lists.newArrayList();
		if(indicatorType.equals("-1")){
			indicatorTypeIds = null;
		}else{
			indicatorTypeIds = MyUtilString.str2LongByPlaceHolder(indicatorType, ",");
		}

		// 查找所有的指标
		List<Indicator> indicatorAll = indicatorService.listByCondition(iname, formsid, indicatorTypeIds, 1, null, 1, null);
		List<Long> indicatorIds = indicatorService.getIndicatorId(indicatorAll);
		if (indicatorIds.isEmpty()) {
			return new Result(Massage.INDICATOR_IS_NULL);
		}

		List<Long> departIds = Lists.newArrayList();
		if(StringUtils.isNotBlank(departId) && !departId.equals("-1")){
			departIds=MyUtilString.str2LongByPlaceHolder(departId, ",");
		}else{
			List<IdNameSname> departmentList = departmentService.getAllByLevelAndArea(null, areaid, 1);
			departIds.addAll(departmentService.getDepartIdsFromIdNameSname(departmentList));
		}

		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicatorIds, yearList, 1);
		List<Map<String, Object>> result = reportService.filter(reportList, yearList);

		logger.info("path:/report/prealarm/area.do+"+"result:"+result);
		return new Result(Massage.SUCCESS, new PageResult(result, result.size()));

	}

	/**
	 * 5.4
	 *
	 * @param indicatorType【必传：-1表示全部】
	 * @param iname	【非必传,模糊指标名称查询】
	 * @param year 【年份  2011,2012,2013】
	 * @return	返回值是value_color
	 *
	 * 适用场景【地市级数据预警统计】
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("report:preAlarm")
	@RequestMapping(value = "/count/city.do")
	@ResponseBody
	public Result count(Long formsid, Long indicatorType, String iname, Integer year) {

		if (!DateFormatUtil.isYear(year) || formsid == null||formsid == 0 || indicatorType == null||indicatorType == 0) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		// 查询条件设置
		if(indicatorType==-1){
			indicatorType = null;
		}
		// 未删除状态数据
		int status = 1;
		// 部门级别 1:国家级;2:省/部级;3:地级市;4:区县级;5:乡镇级;6:其他
		int level = 3;
		int province = 1;

		// 查找所有的部门
		List<Long> departIds = departmentService.getIdsByCondition(level, 1);
		if (departIds.isEmpty()) {
			return new Result(Massage.DEPART_IS_NULL);
		}

		List<Indicator> indicatorList = indicatorService.listByCondition(iname, formsid, indicatorType, province, status, null);
		List<Long> indicators = indicatorService.getIndicatorId(indicatorList);

		List<Integer> yearList = Lists.newArrayList();
		yearList.add(year);
		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicators, yearList, status);

		Area area = areaService.findByCode(CodeName.PROVINCE);
		if(area==null){
			return new Result(Massage.AREA_IS_NULL);
		}

//		// 地域级别 1：国家;2:省，直辖市;3:地级;4:区县;5:乡镇级;6:其他
		List<IdName> areaList = areaService.getIdNameByLevelAndPid(3, area.getId());
		if (areaList.isEmpty()) {
			return new Result(Massage.AREA_IS_NULL);
		}

		List<IdAreaId> departmentIdAreaIdList = departmentService.getAllIdAreaId();
		List<Map<String, Object>> result = Lists.newArrayList();
		for (IdName idName:areaList){
			if(idName==null){
				continue;
			}
			Map<String, Object> map = ReportUtil.countColor(idName.getId(), departmentIdAreaIdList, reportList, year);
			map.put("cname", idName.getName());
			result.add(map);
		}

		return new Result(Massage.SUCCESS, result);
	}

}
